// src/utils/auth.js
import { refreshAccessToken as apiRefreshAccessToken } from '@/api/account'

// 存储令牌和过期时间
export function storeTokens(accessToken, refreshToken, username) {
  const now = new Date()
  const accessTokenExpiry = now.getTime() + 60 * 60 * 1000 // 60分钟后过期

  localStorage.setItem('access_token', accessToken)
  localStorage.setItem('refresh_token', refreshToken)
  localStorage.setItem('access_token_expiry', accessTokenExpiry)
    // 确保在刷新时保留用户名
  if (username) {
    localStorage.setItem('username', username)
  }
}


// 获取用户名
export function getUsername() {
  console.log('调用getUsername:'+localStorage.getItem('username'))
  return localStorage.getItem('username')
}

// 检查用户是否已登录
export function isLoggedIn() {
  const token = localStorage.getItem('access_token')
  return !!token // 如果 token 存在且不为空，则返回 true
}

export function logout() {
  localStorage.removeItem('access_token')
  localStorage.removeItem('refresh_token')
  localStorage.removeItem('username')
  localStorage.removeItem('access_token_expiry')
}

// 检查 access_token 是否过期
export function isAccessTokenExpired() {
  const expiry = localStorage.getItem('access_token_expiry')
  const now = new Date().getTime()
  return now > expiry
}

// 刷新 access_token 并处理业务逻辑
export async function handleRefreshAccessToken() {
  const refreshToken = localStorage.getItem('refresh_token')
  const username = localStorage.getItem('username') // 获取当前用户名

  if (!refreshToken) {
    return false
  }

  try {
    const response = await apiRefreshAccessToken({ refresh: refreshToken })
    const { access } = response.data
    storeTokens(access, refreshToken, username) // 保留用户名
    return true
  } catch (error) {
    console.error('刷新令牌失败:', error)
    return false
  }
}

// 获取访问令牌
export function getAccessToken() {
  return localStorage.getItem('access_token')
}